{% extends "_layout/default.html" %}

{% block stylesheet %}
	{{ super() }}
	<link rel="stylesheet" href="{{ url_for('static', filename='fullcalendar/dist/fullcalendar.min.css') }}">
	<link rel="stylesheet" href="{{ url_for('static', filename='fullcalendar/dist/fullcalendar.print.min.css') }}" media="print">
	<link rel="stylesheet" href="{{ url_for('static', filename='bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css') }}">
{% endblock %}

{% block body_content %}
	<!-- Content Wrapper. Contains page content -->
	<div class="content-wrapper">
    	<!-- Main content -->
	    <section class="content">
			<div class="row">
				<div class="col-md-3">
	        		<div id="external-events-container"></div>
	        	</div>
	        	<!-- /.col -->
	        	<div class="col-md-9">
	          		<div class="box box-primary">
	            		<div class="box-body no-padding">
		              		<!-- THE CALENDAR -->
		              		<div id="calendar"></div>
		            	</div><!-- /.box-body -->	            	
		          	</div><!-- /. box -->
				</div><!-- /.col -->
			</div><!-- /.row -->
		</section><!-- /.content -->
	</div><!-- /.content-wrapper -->
{% endblock %}

{% block bodyscript %}
{{ super() }}
<!-- jQuery UI 1.11.4 -->
<script src="{{ url_for('static', filename='jquery-ui/jquery-ui.min.js') }}"></script>
  
<!-- Slimscroll -->
<script src="{{ url_for('static', filename='jquery-slimscroll/jquery.slimscroll.min.js') }}"></script>

<!-- FastClick -->
<script src="{{ url_for('static', filename='fastclick/lib/fastclick.js') }}"></script>

<!-- fullCalendar -->
<script src="{{ url_for('static', filename='moment/moment.js') }}"></script>
<script src="{{ url_for('static', filename='fullcalendar/dist/fullcalendar.min.js') }}"></script>

<!-- colorpicker -->
<script src="{{ url_for('static', filename='bootstrap-colorpicker/dist/js/bootstrap-colorpicker.min.js') }}"></script>

<!-- Page specific script -->
<script>
var doDeleteTag	= function(ev){
	if(confirm('你确定要删除标签吗?')){
		var tag_id	= jQuery(ev).closest('.external-event').data('id')
		jQuery.post("{{ url_for('calendar_tag_remove', user_tag_id='') }}" + tag_id, function(json){
			if(checkAjaxResponse(json)){
				init_events_container();
			}
		}, 'json');
	}
}

var init_events_container = function(){
	jQuery('#external-events-container').mask();
	jQuery('#external-events-container').load("{{ url_for('calendar_tag') }}", function(){
		jQuery('#external-events-container').unmask();
		/* initialize the external events
		-----------------------------------------------------------------*/
		function init_events(ele) {
			ele.each(function () {
				// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
				// it doesn't need to have a start or end
				var eventObject = {
					title: jQuery.trim(jQuery(this).text()) // use the element's text as the event title
				}

		        // store the Event Object in the DOM element so we can get to it later
          		jQuery(this).data('eventObject', eventObject)

          		// make the event draggable using jQuery UI
          		jQuery(this).draggable({
		            zIndex        : 1070,
		            revert        : true, // will cause the event to go back to its
		            revertDuration: 0  //  original position after the drag
				});
       		});
		}
		
		init_events(jQuery('#external-events div.external-event'))

		//Color chooser button
		jQuery('#color-chooser > li > a').click(function(e){
	        e.preventDefault()
	        var currColor = jQuery(this).data('color')
	        jQuery('#add-new-event').css('background-color', currColor);
	        jQuery('#add-new-event').data('color', currColor);
		});

		//Colorpicker
	    jQuery('.colorpicker-element').colorpicker();
	    jQuery('.colorpicker-element').find(':text').change(function(){
	        var currColor = jQuery(this).val()
	        jQuery('#add-new-event').css('background-color', currColor);
	        jQuery('#add-new-event').data('color', currColor);
		});
     
		jQuery('#add-new-event').click(function(){
	        var post_data = {
				tag_name    : jQuery('#new-event').val(),
				tag_color   : jQuery(this).data('color')
	        };
	        
	    	var ev	= this;
	    	jQuery(ev).prop('disabled', true);
	        jQuery.post("{{ url_for('calendar_tag_add') }}", post_data, function(json){
		    	jQuery(ev).prop('disabled', false);
				if(checkAjaxResponse(json)){
					init_events_container();
				}
	        }, 'json');
		});
	});  
}

var doUpdateEventTime	= function(log_id, start_ymdhis, end_ymdhis){
	jQuery.post("{{ url_for('logger_change_time') }}", {
		_id				: log_id,
		start_ymdhis	: start_ymdhis,
		end_ymdhis		: end_ymdhis
	}, function(json){
		checkAjaxResponse(json);
	}, 'json')
}

jQuery(function () {
    init_events_container();

    /* initialize the calendar
     -----------------------------------------------------------------*/
    jQuery('#calendar').mask();
    jQuery('#calendar').fullCalendar({
		header    	: {
			left  	: 'prev,next, today',
			center	: 'title',
			right	: 'month,agendaWeek,agendaDay'
		},
		buttonText: { 
			today: '今天',
        	month: '月',
        	week : '周',
        	day  : '日'
		},
		eventRender: function(){
			jQuery('#calendar').unmask();
		},
		eventLimit		: true,
		allDaySlot		: false,
		dayNames		: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
		dayNamesShort	: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames		: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        monthNamesShort	: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		events			: { url: "{{ url_for('calendar_events') }}" },
		editable		: true,
		droppable		: true, // this allows things to be dropped onto the calendar !!!
		eventDrop		: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view){
			var _id				= event._id;
			var start_ymdhis	= event.start.format('YYYY-MM-DD HH:mm:ss');
			if(event.end){
				var end_ymdhis		= event.end.format('YYYY-MM-DD HH:mm:ss');				
			}else{
				var end_ymdhis		= start_ymdhis;
			}
			doUpdateEventTime(_id, start_ymdhis, end_ymdhis);
		},
		eventResize		: function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view){
			var _id				= event._id;
			var start_ymdhis	= event.start.format('YYYY-MM-DD HH:mm:ss');
			var end_ymdhis		= event.end.format('YYYY-MM-DD HH:mm:ss');
			doUpdateEventTime(_id, start_ymdhis, end_ymdhis);
		},
		drop			: function (date, allDay, ui, resourceId) { // this function is called when something is dropped
			var tag_id			= $(this).data('id');
			var tag_name		= $(this).data('name');
			var tag_color		= $(this).data('color');
			var start_ymdhis	= '';
			var end_ymdhis		= '';
			
			var start_time		= date._i;
			if(jQuery.isNumeric(start_time)){
				var date		= new Date(start_time);
				var y			= date.getFullYear();
				var m			= date.getMonth() >= 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
				var d			= date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
				start_ymdhis	= y + '-' + m + '-' + d + ' 00:00:00';
				end_ymdhis		= y + '-' + m + '-' + d + ' 23:59:59';
				start_log_ymd	= y + '-' + m + '-' + d;
				start_log_his	= '00:00:00';
				end_log_ymd		= y + '-' + m + '-' + d;
				end_log_his		= '23:59:59';
			}else{
				var y			= start_time[0];
				var m			= start_time[1] >= 9 ? start_time[1] + 1 : '0' + (start_time[1] + 1);
				var d			= start_time[2] > 9 ? start_time[2] : '0' + start_time[2];
				var h			= start_time[3] > 9 ? start_time[3] : '0' + start_time[3];
				var i			= start_time[4] > 9 ? start_time[4] : '0' + start_time[4];
				var s			= start_time[5] > 9 ? start_time[5] : '0' + start_time[5];
				var eh			= start_time[3] >= 9 ? start_time[3] + 1 : '0' + (start_time[3] + 1);
				start_ymdhis	= y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
				end_ymdhis		= y + '-' + m + '-' + d + ' ' + eh + ':' + i + ':' + s;				
				start_log_ymd	= y + '-' + m + '-' + d;
				start_log_his	= h + ':' + i + ':' + s;
				end_log_ymd		= y + '-' + m + '-' + d;
				end_log_his		= eh + ':' + i + ':' + s;
			}

			var post_data	= {
				_id					: '',
				tag_id				: tag_id,
				tag_name			: tag_name,
				tag_color			: tag_color,
				user_log_start_ymd	: start_log_ymd,
				user_log_start_his	: start_log_his,
				user_log_end_ymd	: end_log_ymd,
				user_log_end_his	: end_log_his,
				content				: '',
				satisfy				: 3
			};
			jQuery.post("{{ url_for('logger_save') }}", post_data, function(json){
				if(checkAjaxResponse(json)){
			        // assign it the date that was reported
			        eventObject					= {};
			        eventObject._id				= json._id;
			        eventObject.title			= tag_name;
			        eventObject.start           = moment(start_ymdhis);
			        eventObject.end			  	= moment(end_ymdhis);
			        eventObject.backgroundColor = tag_color;
			        eventObject.borderColor     = tag_color;
			        eventObject.url				= "{{ url_for('logger_form') }}" + '/' + json._id;
			        // render the event on the calendar
			        // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
			        jQuery('#calendar').mask();
			        jQuery('#calendar').fullCalendar('renderEvent', eventObject, true);
				}				
			}, 'json');
		}
	});
});
</script>
{% endblock %}